package com.liaowei.novel.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.liaowei.novel.R;
import com.liaowei.novel.domain.Novel;
import com.liaowei.novel.domain.vo.NovelVO;
import com.liaowei.novel.domain.vo.UserVO;
import com.liaowei.novel.fragment.HomeFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class NovelDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView write_lv;
    private SQLiteDatabase db;
    private TextView detail_name,detail_author,detail_category,detail_description;
    private ImageView detail_coverImage;
    private Button readBtn,collectBtn;
    private String[] from = {"writeId","writeCoverImage", "writeName", "writeAuthor"};
    private int[] to = {R.id.write_id,R.id.write_coverImage, R.id.write_name, R.id.write_author};
    private int novelId;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.novel_detail);
        initView();
        db = SQLiteDatabase.openOrCreateDatabase("/data/data/com.liaowei.novel/databases/novel.db", null);
        Intent intent = getIntent();
        int id = intent.getIntExtra("id",0);
        NovelVO novelVO = getNovelInfo(id);
        setTitle(novelVO.getName()); // 标题设置为小说的名称
        novelId = novelVO.getId();

        // 渲染小说基本信息
        detail_name.setText(novelVO.getName());
        detail_author.setText(novelVO.getUserVO().getNickname());
        detail_category.setText(novelVO.getCategoryName());
        detail_description.setText(novelVO.getDescription());
        Glide.with(this).load(novelVO.getCoverImage()).into(detail_coverImage);

        // 渲染listView
        SimpleAdapter adapter = new SimpleAdapter(this, getWriteData(novelVO), R.layout.write_item, this.from, this.to);
        write_lv.setAdapter(adapter);

        // 判断小说是否在书架里
        if (searchBookShelf(novelId)){
            // 在书架里
            collectBtn.setText("移除书架");
            collectBtn.setBackgroundColor(Color.parseColor("#c75450"));
        }

        // 给按钮绑定单击事件
        collectBtn.setOnClickListener(this);
        readBtn.setOnClickListener(this);
    }

    // 查询书架记录
    @RequiresApi(api = Build.VERSION_CODES.N)
    public boolean searchBookShelf(int id){
        String sql = "select id\n" +
                "from bookshelf\n" +
                "where user_id = 8 and novel_id = " + id;
        Cursor cursor = db.rawQuery(sql, null);
        return cursor.moveToNext();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.collectBtn:
                // 判断小说是加入/移除书架
                if (searchBookShelf(novelId)){
                    // 在书架里，删除书架记录
                    int count = db.delete("bookshelf", "user_id = ? and novel_id = ?",
                            new String[]{"8", String.valueOf(novelId)});
                    if (count > 0){
                        Toast.makeText(this,"移出成功",Toast.LENGTH_LONG).show();
                        collectBtn.setText("加入书架");
                        collectBtn.setBackgroundColor(Color.parseColor("#5e7ce0"));
                    }
                }else {
                    // 不在书架，将该小说加入书架
                    ContentValues cv = new ContentValues();
                    cv.put("user_id",8); // 游客id，ikun
                    cv.put("novel_id",novelId);
                    db.insert("bookshelf",null,cv);
                    Toast.makeText(this,"加入成功",Toast.LENGTH_LONG).show();
                    collectBtn.setText("移出书架");
                    collectBtn.setBackgroundColor(Color.parseColor("#c75450"));
                }
                break;
            case R.id.readBtn:
                Intent intent = new Intent(this,ReadActivity.class);
                intent.putExtra("novelId",novelId);
                intent.putExtra("userId",8);
                startActivity(intent);
                break;
        }
    }

    // 获取该作者写过的小说列表
    public List<Map<String, Object>> getWriteData(NovelVO novelVO){
        List<Map<String, Object>> list = new ArrayList<>();
        List<Novel> novelList = novelVO.getUserVO().getOtherNovelList();
        for (Novel novel : novelList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("writeId",novel.getId());
            map.put("writeCoverImage",novel.getCoverImage());
            map.put("writeName",novel.getName());
            map.put("writeAuthor",novelVO.getUserVO().getNickname());
            list.add(map);
        }
        return list;
    }

    // 获取小说详细信息
    public NovelVO getNovelInfo(int id){
        Cursor cursor = db.rawQuery("select * from novel where id = " + id, null);
        NovelVO novelVO = new NovelVO();
        if (cursor.moveToNext()){
            novelVO.setId(cursor.getInt(cursor.getColumnIndex("id")));
            novelVO.setName(cursor.getString(cursor.getColumnIndex("name")));
            novelVO.setDescription(cursor.getString(cursor.getColumnIndex("description")));
            novelVO.setUserId(cursor.getInt(cursor.getColumnIndex("user_id")));
            novelVO.setCategoryId(cursor.getInt(cursor.getColumnIndex("category_id")));
            novelVO.setCoverImage(cursor.getString(cursor.getColumnIndex("coverImage")));
            novelVO.setCollectNumber(cursor.getLong(cursor.getColumnIndex("collect_number")));

            // 根据categoryId查询分类名称
            Cursor categoryCursor = db.rawQuery("select name from category where id = " + novelVO.getCategoryId(), null);
            if (categoryCursor.moveToNext()){
                novelVO.setCategoryName(categoryCursor.getString(categoryCursor.getColumnIndex("name")));
            }

            // 根据userId查询用户信息
            Cursor userCursor = db.rawQuery("select * from user where id = " + novelVO.getUserId(), null);
            if (userCursor.moveToNext()){
                UserVO userVO = new UserVO();
                userVO.setNickname(userCursor.getString(userCursor.getColumnIndex("nickname")));
                // 根据userId查询该用户写的其他小说
                Cursor otherNovelCursor = db.rawQuery("select * from novel where user_id = " + novelVO.getUserId() + " and id != " + id
                        , null);
                List<Novel> otherNovelList = new ArrayList<>();
                while (otherNovelCursor.moveToNext()){
                    Novel novel = new Novel();
                    novel.setId(otherNovelCursor.getInt(cursor.getColumnIndex("id")));
                    novel.setName(otherNovelCursor.getString(cursor.getColumnIndex("name")));
                    novel.setCoverImage(otherNovelCursor.getString(cursor.getColumnIndex("coverImage")));
                    otherNovelList.add(novel);
                }
                userVO.setOtherNovelList(otherNovelList);
                novelVO.setUserVO(userVO);
            }
        }
        return novelVO;
    }

    // 初始化组件
    public void initView(){
        this.write_lv = findViewById(R.id.write_lv);
        this.detail_name = findViewById(R.id.detail_name);
        this.detail_author = findViewById(R.id.detail_author);
        this.detail_category = findViewById(R.id.detail_category);
        this.detail_description = findViewById(R.id.detail_description);
        this.detail_coverImage = findViewById(R.id.detail_coverImage);
        this.readBtn = findViewById(R.id.readBtn);
        this.collectBtn = findViewById(R.id.collectBtn);
    }

    class SimpleAdapter extends android.widget.SimpleAdapter {
        public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            Map<String, Object> item = (Map<String, Object>) getItem(position);
            String coverImage = (String) item.get("writeCoverImage");
            ImageView iv = v.findViewById(R.id.write_coverImage);
            Glide.with(v).load(coverImage).into(iv);

            LinearLayout line = v.findViewById(R.id.write_item);
            line.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView writeId = v.findViewById(R.id.write_id);
                    String strId = writeId.getText().toString();
                    int id = Integer.parseInt(strId);
                    Intent intent = new Intent(NovelDetailActivity.this, NovelDetailActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

            return v;
        }
    }
}